package com.iwords.android;

import java.net.URLEncoder;

import org.apache.http.client.methods.HttpPost;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebView;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.util.AlixId;
import com.alipay.util.BaseHelper;
import com.alipay.util.MobileSecurePayHelper;
import com.alipay.util.MobileSecurePayer;
import com.alipay.util.OrderUtil;
import com.alipay.util.PartnerConfig;
import com.alipay.util.ResultChecker;

import android.content.DialogInterface.OnClickListener;

public class AlipayAdActivity extends Activity {
	static String TAG = "5iwords.com";
	// 安全支付启动时进度对话框
	private ProgressDialog mProgress = null;
	// 订单信息工具类
	private OrderUtil util = null;
	
	private CheckBox box1;
	private CheckBox box2;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.alipay_ad);
		this.box1 = (CheckBox)this.findViewById(R.id.box1);
		this.box2 = (CheckBox)this.findViewById(R.id.box2);
		
		// 检查支付宝安全服务是否已经安装
		MobileSecurePayHelper mspHelper = new MobileSecurePayHelper(this);
		mspHelper.detectMobile_sp();
	}
	
	private void vibrate(){
		Vibrator mVibrator = (Vibrator)getApplication().getSystemService(android.app.Service.VIBRATOR_SERVICE);
		mVibrator.vibrate(new long[]{50,50},-1);
	}
	public void alipayStart(View view) {
		this.vibrate();
		//
		// 检查支付宝安全服务是否已经安装
		MobileSecurePayHelper mspHelper = new MobileSecurePayHelper(this);
		boolean isMobile_spExist = mspHelper.detectMobile_sp();
		// 初始化订单信息工具类
		util = new OrderUtil();

		if (!isMobile_spExist)
			return;

		// 检查partnerID seller 等信息
		if (!util.checkInfo()) {
			BaseHelper.showDialog(AlipayAdActivity.this, "提示",
					"缺少partner或者seller，请在src/com/alipay/android/appDemo4/PartnerConfig.java中增加。", R.drawable.infoicon,
					null);
			return;
		}

		// 对订单进行支付
		try {
			// 生成订单
			String orderInfo = getOrderInfo();

			String signType = util.getSignType();
			// 订单签名
			String strsign = util.sign(signType, orderInfo);
			strsign = URLEncoder.encode(strsign);
			String info = orderInfo + "&sign=" + "\"" + strsign + "\"" + "&" + signType;
			//从服务器端获取订单info
			
			// 开始支付
			MobileSecurePayer msp = new MobileSecurePayer();
			// 返回是否正在支付
			boolean bRet = msp.pay(info, mHandler, AlixId.RQF_PAY, this);

			if (bRet) {
				// 显示进度对话框 表示正在进行支付
				closeProgress();
				mProgress = BaseHelper.showProgress(this, null, "正在支付", false, true);
			} else
				;
		} catch (Exception ex) {
			ex.printStackTrace();
			Toast.makeText(AlipayAdActivity.this, R.string.remote_call_failed, Toast.LENGTH_SHORT).show();
		}
	}

	/** 组织发送给支付宝的订单信息。 */
	private String getOrderInfo() {
		// 所有参数意义请参考文档，这里不做赘述
		String total_fee = "20.00";
		if(this.box2.isChecked()){
			total_fee = "30.00";
		}
		String strOrderInfo = "partner=" + "\"" + PartnerConfig.PARTNER + "\"";
		strOrderInfo += "&";
		strOrderInfo += "seller=" + "\"" + PartnerConfig.SELLER + "\"";
		strOrderInfo += "&";
		strOrderInfo += "out_trade_no=" + "\"" + alipayStart(total_fee) + "\"";
		strOrderInfo += "&";
		strOrderInfo += "subject=" + "\"爱词软件和技术服务费\"";
		strOrderInfo += "&";
		strOrderInfo += "body=" + "\"" + ((IWordsApp) getApplicationContext()).getUser().getEmail() + "\"";// 这里应该写上用户名称，便于追查是谁付的。
		strOrderInfo += "&";
		strOrderInfo += "total_fee=" + "\"" + total_fee + "\"";
		strOrderInfo += "&";
		strOrderInfo += "notify_url=" + "\"" + getResources().getString(R.string.alipay_notify) + "\"";
		return strOrderInfo;
	}

	//
	// 接收支付结果
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			try {
				final String strRet = (String) msg.obj;

				switch (msg.what) {
				case AlixId.RQF_PAY: {
					closeProgress();
					// BaseHelper.log(TAG, strRet);
					//System.out.println("手机安全支付返回消息： strRet = " + strRet);
					try {
						String memo = "memo=";
						int imemoStart = strRet.indexOf("memo=");
						imemoStart += memo.length();
						int imemoEnd = strRet.indexOf(";result=");
						memo = strRet.substring(imemoStart, imemoEnd);
						// 验签
						final ResultChecker resultChecker = new ResultChecker(strRet);
						int retVal = resultChecker.checkSign();

						// 验签失败
						if (retVal == ResultChecker.RESULT_CHECK_SIGN_FAILED) {
							BaseHelper.showDialog(AlipayAdActivity.this, "提示",
									getResources().getString(R.string.check_sign_failed),
									android.R.drawable.ic_dialog_alert, null);
						} else {// 验签成功
							if (resultChecker.isPayOk()) {// 支付结果OK，将订单的状态设置为已经处理。
								// final String memostr = memo;
								BaseHelper.showDialog(AlipayAdActivity.this, "提示", memo, R.drawable.infoicon,
										new OnClickListener() {
											@Override
											public void onClick(DialogInterface dialog, int which) {
												// System.out.println("验签成功: memo = " + memostr);
												commitOutTrade(strRet);
												close();
											}

										});
							} else {// 支付结果不OK，提示信息给用户，但不调用alipayReturn接口，不通知爱词服务器
								// final String memostr = memo;
								BaseHelper.showDialog(AlipayAdActivity.this, "提示", memo, R.drawable.infoicon,
										new OnClickListener() {
											@Override
											public void onClick(DialogInterface dialog, int which) {
												// System.out.println("验签成功: memo = " + memostr);
												close();
											}
										});
							}
						}

					} catch (Exception e) {
						e.printStackTrace();
						BaseHelper.showDialog(AlipayAdActivity.this, "提示", strRet, R.drawable.infoicon, null);
					}
				}
					break;
				}

				super.handleMessage(msg);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};


	/** 爱词网站订单ID，向服务器端发送请求，生成订单，并返回生成订单的ID */
	private Long alipayStart(String total_fee) {
		IWordsApp iWordsApp = (IWordsApp) getApplicationContext();
		Long userid = iWordsApp.getUser().getUserid();
		String href = iWordsApp.getResources().getString(R.string.alipay_trade_start);
		href = href + "?total_fee=" + total_fee;
		href = href + "&userid=" + userid;
		HttpPost request = new HttpPost(href);
		//System.out.println("$$$$$$$$$AlipayActivity.alipayStart() href = " + href);
		try {
			JSONObject jSONObject = ServerAccessor.access(iWordsApp, request);
			boolean success = jSONObject.getBoolean("isSuccess");
			//System.out.println("IWords.loginHandler() success = " + success);
			if (success) {
				JSONObject jsonLib = jSONObject.getJSONObject("defaultValue");
				//System.out.println("IWords.loginHandler() out_trade_id = " + jsonLib.getLong("out_trade_id"));
				return jsonLib.getLong("out_trade_id");
			} else {
				displayMessage(CodeUtils.decode(jSONObject.getString("message")));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private void displayMessage(String message) {
		Toast t1 = Toast.makeText(getApplication(), message, Toast.LENGTH_LONG * 4);
		t1.show();
	}

	private Long getOutTradeNo(String memostr) {
		try {
			int signContentEnd = memostr.indexOf(";result=");
			String result = memostr.substring(signContentEnd + 1, memostr.length() - 1);
			//System.out.println("AlipayActivity.getOutTradeNo() result = " + result);
			JSONObject objResult = BaseHelper.string2JSON(result, "&");
			String out_trade_no = objResult.getString("out_trade_no");
			out_trade_no = out_trade_no.replace("\"", "");
			//System.out.println("AlipayActivity.getOutTradeNo() out_trade_no = " + out_trade_no);
			return Long.valueOf(out_trade_no);
		} catch (Exception e) {
			BaseHelper.showDialog(AlipayAdActivity.this, "提示", e.getMessage(), android.R.drawable.ic_dialog_alert, null);
		}
		return null;
	}
	/** 爱词网站订单ID，向服务器端发送请求，生成订单，并返回生成订单的ID */
	private void commitOutTrade(String strRet) {
		Long out_trade_no = getOutTradeNo(strRet);
		IWordsApp iWordsApp = (IWordsApp) getApplicationContext();
		Long userid = iWordsApp.getUser().getUserid();
		String href = iWordsApp.getResources().getString(R.string.alipay_trade_return);
		href = href + "?out_trade_no=" + out_trade_no + "&userid=" + userid;
		//System.out.println("$$$$$$$$$AlipayActivity.commitOutTrade() href = " + href);
		HttpPost request = new HttpPost(href);
		String message = "";
		try {
			JSONObject jSONObject = ServerAccessor.access(iWordsApp, request);
			boolean success = jSONObject.getBoolean("isSuccess");
			// System.out.println("IWords.loginHandler() success = " + success);
			if (success) {
				message = "恭喜，您已经称为正式用户。";
			} else {
				message = "开通爱词帐号出现问题，请联系5iwords.com@gmail.com.";
			}
		} catch (Exception e) {
			e.printStackTrace();
			message = "开通爱词帐号出现问题:" + e.getMessage() + "，请联系5iwords.com@gmail.com.";
		}
		this.alertDialog = BaseHelper.showDialog(AlipayAdActivity.this, "提示", message, R.drawable.infoicon, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				close();
			}
		});
	}

	//
	// the OnCancelListener for lephone platform.
	public static class AlixOnCancelListener implements DialogInterface.OnCancelListener {
		Activity mcontext;

		public AlixOnCancelListener(Activity context) {
			mcontext = context;
		}

		public void onCancel(DialogInterface dialog) {
			mcontext.onKeyDown(KeyEvent.KEYCODE_BACK, null);
		}
	}

	//
	// close the progress bar
	void closeProgress() {
		try {
			if (mProgress != null) {
				mProgress.dismiss();
				mProgress = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			BaseHelper.log(TAG, "onKeyDown back");

			this.finish();
			return true;
		}

		return false;
	}

	private AlertDialog alertDialog;
	private void close() {
		if(alertDialog != null){
			alertDialog.dismiss();
		}
		this.finish();
	}

	//
	@Override
	public void onDestroy() {
		super.onDestroy();
		try {
			mProgress.dismiss();
		} catch (Exception e) {
			// e.printStackTrace();
		}
	}
	
	public void onResume() {
		super.onResume(); 
		com.mobclick.android.MobclickAgent.onResume(this);
	}
	
	public void onPause() {
		super.onPause(); 
		com.mobclick.android.MobclickAgent.onPause(this);
	}
}
